<template>
  <view class="orders">
    <view class="header">
      <text class="title">订单管理</text>
      <button class="btn-export" @click="exportOrders">导出订单</button>
    </view>

    <view class="filters">
      <view class="filter-row">
        <input class="search-input" v-model="searchKeyword" placeholder="搜索订单号或用户信息" @input="searchOrders" />
        <picker :value="statusIndex" :range="statusOptions" @change="onStatusChange">
          <view class="filter-picker">{{ statusOptions[statusIndex] }}</view>
        </picker>
      </view>
      <view class="filter-row">
        <picker :value="paymentStatusIndex" :range="paymentStatusOptions" @change="onPaymentStatusChange">
          <view class="filter-picker">{{ paymentStatusOptions[paymentStatusIndex] }}</view>
        </picker>
        <picker :value="paymentMethodIndex" :range="paymentMethodOptions" @change="onPaymentMethodChange">
          <view class="filter-picker">{{ paymentMethodOptions[paymentMethodIndex] }}</view>
        </picker>
      </view>
      <view class="filter-row">
        <input class="date-input" type="date" v-model="startDate" @change="loadOrders(1)" placeholder="开始日期" />
        <input class="date-input" type="date" v-model="endDate" @change="loadOrders(1)" placeholder="结束日期" />
      </view>
    </view>

    <view class="order-stats">
      <view class="stat-item">
        <text class="stat-number">{{ orderStats.total }}</text>
        <text class="stat-label">总订单</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ orderStats.pending }}</text>
        <text class="stat-label">待处理</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ orderStats.completed }}</text>
        <text class="stat-label">已完成</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">¥{{ orderStats.totalAmount }}</text>
        <text class="stat-label">总金额</text>
      </view>
    </view>

    <view class="order-list">
      <view v-for="order in orders" :key="order.id" class="order-item">
        <view class="order-header">
          <text class="order-number">订单号: {{ order.orderNumber }}</text>
          <text class="order-date">{{ formatDate(order.createdAt) }}</text>
        </view>

        <view class="order-content">
          <view class="order-info">
            <text class="user-info">用户: {{ getUserDisplayName(order.user) }}</text>
            <text class="product-info">商品: {{ getProductName(order.product) }}</text>
            <text class="quantity-info">数量: {{ order.quantity }}</text>
            <text class="amount-info">金额: ¥{{ order.finalAmount }}</text>
            <text class="payment-info">支付方式: {{ getPaymentMethodText(order.paymentMethod) }}</text>
          </view>

          <view class="order-status">
            <text class="status-badge" :class="[getOrderStatusClass(order.status)]">
              {{ getOrderStatusText(order.status) }}
            </text>
            <text class="payment-status" :class="[getPaymentStatusClass(order.paymentStatus)]">
              {{ getPaymentStatusText(order.paymentStatus) }}
            </text>
          </view>
        </view>

        <view class="order-actions">
          <button class="btn-detail" @click="viewOrderDetail(order)">详情</button>
          <button v-if="order.status === 'pending'" class="btn-confirm" @click="updateOrderStatus(order, 'confirmed')">
            确认
          </button>
          <button v-if="order.status === 'confirmed'" class="btn-process"
            @click="updateOrderStatus(order, 'processing')">
            处理
          </button>
          <button v-if="order.status === 'processing'" class="btn-complete"
            @click="updateOrderStatus(order, 'completed')">
            完成
          </button>
          <button v-if="['pending', 'confirmed'].includes(order.status)" class="btn-cancel"
            @click="updateOrderStatus(order, 'cancelled')">
            取消
          </button>
          <button v-if="order.paymentStatus === 'paid' && ['completed', 'cancelled'].includes(order.status)"
            class="btn-refund" @click="processRefund(order)">
            退款
          </button>
        </view>
      </view>
    </view>

    <view class="pagination">
      <button class="page-btn" :disabled="currentPage <= 1" @click="loadOrders(currentPage - 1)">
        上一页
      </button>
      <text class="page-info">{{ currentPage }} / {{ totalPages }}</text>
      <button class="page-btn" :disabled="currentPage >= totalPages" @click="loadOrders(currentPage + 1)">
        下一页
      </button>
    </view>

    <!-- 订单详情弹窗 -->
    <view v-if="showOrderDetail" class="modal-overlay" @click="closeOrderDetail">
      <view class="modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">订单详情</text>
          <text class="modal-close" @click="closeOrderDetail">×</text>
        </view>
        <view class="modal-body">
          <view v-if="selectedOrder" class="order-detail">
            <view class="detail-section">
              <text class="section-title">基本信息</text>
              <view class="detail-item">
                <text class="detail-label">订单号:</text>
                <text class="detail-value">{{ selectedOrder.orderNumber }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">创建时间:</text>
                <text class="detail-value">{{ formatDate(selectedOrder.createdAt) }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">订单状态:</text>
                <text class="detail-value">{{ getOrderStatusText(selectedOrder.status) }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">支付状态:</text>
                <text class="detail-value">{{ getPaymentStatusText(selectedOrder.paymentStatus) }}</text>
              </view>
            </view>

            <view class="detail-section">
              <text class="section-title">用户信息</text>
              <view class="detail-item">
                <text class="detail-label">用户昵称:</text>
                <text class="detail-value">{{ selectedOrder.user ? (selectedOrder.user.nickname || '未设置') : '未设置'
                  }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">手机号:</text>
                <text class="detail-value">{{ selectedOrder.user ? (selectedOrder.user.phone || '未绑定') : '未绑定' }}</text>
              </view>
            </view>

            <view class="detail-section">
              <text class="section-title">商品信息</text>
              <view class="detail-item">
                <text class="detail-label">商品名称:</text>
                <text class="detail-value">{{ selectedOrder.product ? (selectedOrder.product.name || '未知商品') : '未知商品'
                  }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">商品价格:</text>
                <text class="detail-value">¥{{ selectedOrder.product ? (selectedOrder.product.price || 0) : 0 }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">购买数量:</text>
                <text class="detail-value">{{ selectedOrder.quantity }}</text>
              </view>
            </view>

            <view class="detail-section">
              <text class="section-title">金额信息</text>
              <view class="detail-item">
                <text class="detail-label">原价:</text>
                <text class="detail-value">¥{{ selectedOrder.originalAmount }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">折扣:</text>
                <text class="detail-value">¥{{ selectedOrder.discountAmount || 0 }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">积分抵扣:</text>
                <text class="detail-value">{{ selectedOrder.pointsUsed || 0 }} 积分</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">实付金额:</text>
                <text class="detail-value">¥{{ selectedOrder.finalAmount }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-close" @click="closeOrderDetail">关闭</button>
        </view>
      </view>
    </view>

    <!-- 退款弹窗 -->
    <view v-if="showRefundModal" class="modal-overlay" @click="closeRefundModal">
      <view class="modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">处理退款</text>
          <text class="modal-close" @click="closeRefundModal">×</text>
        </view>
        <view class="modal-body">
          <view class="refund-info">
            <text class="order-amount">订单金额: ¥{{ refundOrder ? refundOrder.finalAmount : 0 }}</text>
          </view>
          <view class="form-group">
            <text class="form-label">退款金额</text>
            <input class="form-input" type="number" v-model="refundForm.amount" placeholder="请输入退款金额" />
          </view>
          <view class="form-group">
            <text class="form-label">退款原因</text>
            <textarea class="form-textarea" v-model="refundForm.reason" placeholder="请输入退款原因"></textarea>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeRefundModal">取消</button>
          <button class="btn-confirm" @click="confirmRefund">确认退款</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orders: [],
      searchKeyword: '',
      currentPage: 1,
      totalPages: 1,
      pageSize: 10,

      // 筛选条件
      statusOptions: ['全部状态', '待处理', '已确认', '处理中', '打印中', '已完成', '已取消'],
      statusIndex: 0,
      paymentStatusOptions: ['全部支付状态', '未支付', '已支付', '已退款'],
      paymentStatusIndex: 0,
      paymentMethodOptions: ['全部支付方式', '微信支付', '支付宝', '积分兑换'],
      paymentMethodIndex: 0,
      startDate: '',
      endDate: '',

      // 订单统计
      orderStats: {
        total: 0,
        pending: 0,
        completed: 0,
        totalAmount: 0
      },

      // 订单详情
      showOrderDetail: false,
      selectedOrder: null,

      // 退款处理
      showRefundModal: false,
      refundOrder: null,
      refundForm: {
        amount: 0,
        reason: ''
      }
    }
  },

  onLoad() {
    this.loadOrders()
    this.loadOrderStats()
  },

  methods: {
    async loadOrders(page = 1) {
      try {
        const token = uni.getStorageSync('token')
        if (!token) {
          uni.navigateTo({ url: '/pages/auth/login' })
          return
        }

        const params = new URLSearchParams({
          page: page.toString(),
          limit: this.pageSize.toString(),
          search: this.searchKeyword
        })

        if (this.statusIndex > 0) {
          const statusMap = {
            1: 'pending', 2: 'confirmed', 3: 'processing',
            4: 'printing', 5: 'completed', 6: 'cancelled'
          }
          params.append('status', statusMap[this.statusIndex])
        }

        if (this.paymentStatusIndex > 0) {
          const paymentStatusMap = { 1: 'unpaid', 2: 'paid', 3: 'refunded' }
          params.append('paymentStatus', paymentStatusMap[this.paymentStatusIndex])
        }

        if (this.paymentMethodIndex > 0) {
          const paymentMethodMap = { 1: 'wechat', 2: 'alipay', 3: 'points' }
          params.append('paymentMethod', paymentMethodMap[this.paymentMethodIndex])
        }

        if (this.startDate) {
          params.append('startDate', this.startDate)
        }

        if (this.endDate) {
          params.append('endDate', this.endDate)
        }

        const res = await uni.request({
          url: `https://ydy.lg1012.cn/api/admin/orders?${params.toString()}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (res.data.success) {
          this.orders = res.data.data.orders || []
          this.currentPage = res.data.data.currentPage || 1
          this.totalPages = res.data.data.totalPages || 1
        }
      } catch (error) {
        console.error('加载订单失败:', error)
        uni.showToast({
          title: '加载订单失败',
          icon: 'none'
        })
      }
    },

    async loadOrderStats() {
      try {
        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: 'https://ydy.lg1012.cn/api/admin/orders/analytics/overview',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (res.data.success) {
          this.orderStats = res.data.data
        }
      } catch (error) {
        console.error('加载订单统计失败:', error)
      }
    },

    searchOrders() {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.loadOrders(1)
      }, 500)
    },

    onStatusChange(e) {
      this.statusIndex = e.detail.value
      this.loadOrders(1)
    },

    onPaymentStatusChange(e) {
      this.paymentStatusIndex = e.detail.value
      this.loadOrders(1)
    },

    onPaymentMethodChange(e) {
      this.paymentMethodIndex = e.detail.value
      this.loadOrders(1)
    },

    async updateOrderStatus(order, newStatus) {
      const statusText = this.getOrderStatusText(newStatus)
      uni.showModal({
        title: '确认操作',
        content: `确定要将订单状态更新为"${statusText}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              const updateRes = await uni.request({
                url: `https://ydy.lg1012.cn/api/admin/orders/${order.id}/status`,
                method: 'PUT',
                header: {
                  'Authorization': `Bearer ${token}`,
                  'Content-Type': 'application/json'
                },
                data: {
                  status: newStatus,
                  notes: `管理员操作：更新状态为${statusText}`
                }
              })

              if (updateRes.data.success) {
                uni.showToast({ title: '状态更新成功' })
                this.loadOrders(this.currentPage)
                this.loadOrderStats()
              }
            } catch (error) {
              uni.showToast({ title: '状态更新失败', icon: 'none' })
            }
          }
        }
      })
    },

    viewOrderDetail(order) {
      this.selectedOrder = order
      this.showOrderDetail = true
    },

    closeOrderDetail() {
      this.showOrderDetail = false
      this.selectedOrder = null
    },

    processRefund(order) {
      this.refundOrder = order
      this.refundForm = {
        amount: order.finalAmount,
        reason: ''
      }
      this.showRefundModal = true
    },

    closeRefundModal() {
      this.showRefundModal = false
      this.refundOrder = null
      this.refundForm = {
        amount: 0,
        reason: ''
      }
    },

    async confirmRefund() {
      if (!this.refundForm.amount || this.refundForm.amount <= 0) {
        uni.showToast({ title: '请输入有效的退款金额', icon: 'none' })
        return
      }

      if (!this.refundForm.reason) {
        uni.showToast({ title: '请输入退款原因', icon: 'none' })
        return
      }

      try {
        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: `https://ydy.lg1012.cn/api/admin/orders/${this.refundOrder.id}/refund`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: {
            refundAmount: this.refundForm.amount,
            refundReason: this.refundForm.reason
          }
        })

        if (res.data.success) {
          uni.showToast({ title: '退款处理成功' })
          this.closeRefundModal()
          this.loadOrders(this.currentPage)
          this.loadOrderStats()
        }
      } catch (error) {
        uni.showToast({ title: '退款处理失败', icon: 'none' })
      }
    },

    async exportOrders() {
      try {
        const token = uni.getStorageSync('token')
        const params = new URLSearchParams()

        if (this.searchKeyword) params.append('search', this.searchKeyword)
        if (this.startDate) params.append('startDate', this.startDate)
        if (this.endDate) params.append('endDate', this.endDate)

        const res = await uni.request({
          url: `https://ydy.lg1012.cn/api/admin/orders/export/excel?${params.toString()}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (res.data.success) {
          uni.showToast({ title: '导出成功' })
          // 这里可以添加下载逻辑
        }
      } catch (error) {
        uni.showToast({ title: '导出失败', icon: 'none' })
      }
    },

    getOrderStatusClass(status) {
      const classMap = {
        'pending': 'status-pending',
        'confirmed': 'status-confirmed',
        'processing': 'status-processing',
        'printing': 'status-printing',
        'completed': 'status-completed',
        'cancelled': 'status-cancelled'
      }
      return classMap[status] || 'status-default'
    },

    getOrderStatusText(status) {
      const textMap = {
        'pending': '待处理',
        'confirmed': '已确认',
        'processing': '处理中',
        'printing': '打印中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return textMap[status] || status
    },

    getPaymentStatusClass(status) {
      const classMap = {
        'unpaid': 'payment-unpaid',
        'paid': 'payment-paid',
        'refunded': 'payment-refunded'
      }
      return classMap[status] || 'payment-default'
    },

    getPaymentStatusText(status) {
      const textMap = {
        'unpaid': '未支付',
        'paid': '已支付',
        'refunded': '已退款'
      }
      return textMap[status] || status
    },

    getPaymentMethodText(method) {
      const textMap = {
        'wechat': '微信支付',
        'alipay': '支付宝',
        'points': '积分兑换'
      }
      return textMap[method] || method
    },

    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    },

    getUserDisplayName(user) {
      if (!user) return '未知用户'
      return user.nickname || user.phone || '未知用户'
    },

    getProductName(product) {
      if (!product) return '未知商品'
      return product.name || '未知商品'
    }
  }
}
</script>

<style scoped>
.orders {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.btn-export {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.filters {
  background: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.search-input,
.date-input {
  flex: 1;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.filter-picker {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
  min-width: 200rpx;
  text-align: center;
}

.order-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.stat-item {
  background: white;
  padding: 30rpx;
  border-radius: 12rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.stat-number {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #007bff;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.order-list {
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 30rpx;
}

.order-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.order-date {
  font-size: 24rpx;
  color: #666;
}

.order-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.order-info {
  flex: 1;
}

.user-info,
.product-info,
.quantity-info,
.amount-info,
.payment-info {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.order-status {
  text-align: right;
}

.status-badge {
  display: block;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: white;
  margin-bottom: 8rpx;
}

.status-pending {
  background-color: #ffc107;
}

.status-confirmed {
  background-color: #17a2b8;
}

.status-processing {
  background-color: #007bff;
}

.status-printing {
  background-color: #6f42c1;
}

.status-completed {
  background-color: #28a745;
}

.status-cancelled {
  background-color: #dc3545;
}

.payment-status {
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
}

.payment-unpaid {
  background-color: #fff3cd;
  color: #856404;
}

.payment-paid {
  background-color: #d4edda;
  color: #155724;
}

.payment-refunded {
  background-color: #f8d7da;
  color: #721c24;
}

.order-actions {
  display: flex;
  gap: 12rpx;
  flex-wrap: wrap;
}

.btn-detail,
.btn-confirm,
.btn-process,
.btn-complete,
.btn-cancel,
.btn-refund {
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  color: white;
}

.btn-detail {
  background-color: #6c757d;
}

.btn-confirm {
  background-color: #17a2b8;
}

.btn-process {
  background-color: #007bff;
}

.btn-complete {
  background-color: #28a745;
}

.btn-cancel {
  background-color: #dc3545;
}

.btn-refund {
  background-color: #ffc107;
  color: #333;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30rpx;
  padding: 30rpx;
}

.page-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.page-btn:disabled {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
}

.modal-body {
  padding: 30rpx;
}

.order-detail {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.detail-section {
  border-bottom: 1rpx solid #eee;
  padding-bottom: 20rpx;
}

.detail-section:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.detail-label {
  font-size: 24rpx;
  color: #666;
}

.detail-value {
  font-size: 24rpx;
  color: #333;
}

.refund-info {
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.order-amount {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.form-textarea {
  height: 120rpx;
  resize: vertical;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn-close,
.btn-cancel,
.btn-confirm {
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.btn-close {
  background-color: #6c757d;
  color: white;
}

.btn-cancel {
  background-color: #6c757d;
  color: white;
}

.btn-confirm {
  background-color: #007bff;
  color: white;
}
</style>